import Cookies from "js-cookie";
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
// import { App } from "vue";
import store from "../store";
import { getAdminInfoApi } from "../request/api";
const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login/login.vue"),
  },
  // {
  //   path: "/homepage",
  //   name: "homepage",
  //   component: () => import("../views/homepage/homePage.vue"),
  // },
];
console.log("routes:" + routes);
const router = createRouter({
  history: createWebHashHistory(),
  routes, //路由配置
});
//根据getter菜单生成规则
const genRoutes = () => {
  //菜单列表配置
  const menus = store.getters.getNewMenus;
  console.log(menus);
  //循环菜单
  for (let key in menus) {
    //unshit?
    const newRoute: RouteRecordRaw = {
      path: "/" + menus[key].name,
      name: menus[key].name,
      component: () => import("../views/homepage/homePage.vue"),
      redirect: "/" + menus[key].name + "/" + menus[key].children[0].name,
      children: [],
    };
    for (let i = 0; i < menus[key].children.length; i++) {
      newRoute.children?.push({
        path: menus[key].children[i].name,
        name: menus[key].children[i].name,
        component: () =>
          import(
            `../views/${menus[key].name}/${menus[key].children[i].name}.vue`
          ),
      });
    }
    //动态路由添加
    router.addRoute(newRoute);
  }

  //动态添加首页
  router.addRoute({
    path: "/",
    name: "index",
    component: () => import("../views/homepage/homePage.vue"),
    //重定向
    redirect: "/index",
    children: [
      {
        path: "/index",
        name: "name",
        component: () => import("../views/index/index.vue"),
      },
    ],
  });
};
//前置导航守卫，解决刷新获取不到数据的问题
router.beforeEach((to, from, next) => {
  //条件token vuex列表为空
  const token = Cookies.get("token");
  if (token && store.state.menus.length === 0) {
    store.dispatch("getAdminInfo").then(() => {
      genRoutes();
      next(to);
    });
  }
  //解决非首次登录
  else if (
    token &&
    store.state.menus.length !== 0 &&
    from.path === "/login" &&
    to.path === "/homepage"
  ) {
    genRoutes();
    next("/index");
  }
  //解决token过期的问题
  // else if (!token && to.path !== "login") {
  //   console.log("token过期了");
  //   next("/login");
  // }
  //解决token还在请求登录页面
  else if (token && to.path === "login") {
    console.log("token有效，无需再次登录");
    next(from);
  } else {
    next();
  }
});

export default router;
// export const initRouter = (app: App<Element>) => {
//   app.use(router);
// };
